package cn.cheegon.blog.service.impl;

import cn.cheegon.blog.common.api.CommonPage;
import cn.cheegon.blog.common.exception.Asserts;
import cn.cheegon.blog.entity.dto.CommentDto;
import cn.cheegon.blog.entity.dto.CommentTreeDto;
import cn.cheegon.blog.mapper.CmsBlogMapper;
import cn.cheegon.blog.mapper.UmsAdminMapper;
import cn.cheegon.blog.model.CmsBlog;
import cn.cheegon.blog.model.CmsComment;
import cn.cheegon.blog.mapper.CmsCommentMapper;
import cn.cheegon.blog.model.UmsAdmin;
import cn.cheegon.blog.service.CmsCommentService;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 评论表 服务实现类
 * </p>
 *
 * @author cheegon
 * @since 2024-06-21
 */
@Service
public class CmsCommentServiceImpl extends ServiceImpl<CmsCommentMapper, CmsComment> implements CmsCommentService {
    @Autowired
    UmsAdminMapper adminMapper;

    @Autowired
    CmsBlogMapper blogMapper;

    @Override
    public CommonPage<CommentDto> getList(Long blogId, Integer status, int pageNum, int pageSize) {
        QueryWrapper<CmsComment> queryWrapper = new QueryWrapper<>();
        if (blogId != null) {
            queryWrapper.eq("blog_id", blogId);
        }
        if (status != null) {
            queryWrapper.eq("status", status);
        }
        queryWrapper.orderByDesc("create_time");
        Page<CmsComment> page = this.baseMapper.selectPage(new Page<CmsComment>(pageNum, pageSize), queryWrapper);
        if (CollectionUtils.isEmpty(page.getRecords())) {
            return CommonPage.emptyPage(page);
        }
        //用户信息
        List<Long> uidList = page.getRecords().stream().map(CmsComment::getUid).toList();
        QueryWrapper<UmsAdmin> userWrapper = new QueryWrapper<>();
        userWrapper.in("id", uidList);
        List<UmsAdmin> umsAdmins = adminMapper.selectList(userWrapper);
        if (umsAdmins == null) {
            umsAdmins = new ArrayList<>();
        }
        Map<Long, UmsAdmin> adminMap = umsAdmins.stream().collect(Collectors.toMap(UmsAdmin::getId, it -> it));
        //博客信息
        List<Long> blogIdList = page.getRecords().stream().map(CmsComment::getBlogId).toList();
        QueryWrapper<CmsBlog> blogWrapper = new QueryWrapper<>();
        userWrapper.in("id", blogIdList);
        List<CmsBlog> cmsBlogs = blogMapper.selectList(blogWrapper);
        if (cmsBlogs == null) {
            cmsBlogs = new ArrayList<>();
        }
        Map<Long, CmsBlog> blogMap = cmsBlogs.stream().collect(Collectors.toMap(CmsBlog::getId, it -> it));
        //数据填充
        List<CommentDto> dtoList = page.getRecords().stream().map(it -> {
            CommentDto bean = BeanUtil.toBean(it, CommentDto.class);
            UmsAdmin umsAdmin = adminMap.get(it.getUid());
            if (umsAdmin != null) {
                bean.setAvatar(umsAdmin.getAvatar());
                bean.setNickname(umsAdmin.getNickname());
            }
            CmsBlog cmsBlog = blogMap.get(it.getBlogId());
            if (cmsBlog != null) {
                bean.setBlogTitle(cmsBlog.getTitle());
            }
            return bean;
        }).toList();
        return CommonPage.restPage(page, dtoList);
    }

    @Override
    public CommonPage<CommentTreeDto> getTreeList(Long blogId, Long parentId, int pageNum, int pageSize) {
        QueryWrapper<CmsComment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("blog_id", blogId);
        queryWrapper.eq("root_comment_id", parentId);
        queryWrapper.orderByDesc("create_time");
        Page<CmsComment> page = this.baseMapper.selectPage(new Page<CmsComment>(pageNum, pageSize), queryWrapper);
        List<CmsComment> records = page.getRecords();
        if (CollectionUtils.isEmpty(records)) {
            return CommonPage.emptyPage(page);
        }
        List<Long> uidList = new ArrayList<>();
        uidList.addAll(records.stream().map(CmsComment::getUid).toList());
        List<CommentTreeDto> dtoList = records.stream().map(it -> BeanUtil.toBean(it, CommentTreeDto.class)).toList();
        // 查找子条目
        dtoList.forEach(it -> {
            QueryWrapper<CmsComment> childWrapper = new QueryWrapper<>();
            childWrapper.eq("root_comment_id", it.getId());
            List<CmsComment> cmsComments = this.baseMapper.selectList(childWrapper);
            if (CollectionUtils.isEmpty(cmsComments)) {
                it.setChildren(new ArrayList<>());
            } else {
                it.setChildren(BeanUtil.copyToList(cmsComments, CommentTreeDto.class));
                uidList.addAll(cmsComments.stream().map(CmsComment::getUid).toList());
            }
        });
        //查找用户信息
        List<Long> distinctUidList = uidList.stream().distinct().toList();
        QueryWrapper<UmsAdmin> userWrapper = new QueryWrapper<>();
        userWrapper.in("id", distinctUidList);
        List<UmsAdmin> umsAdmins = adminMapper.selectList(userWrapper);
        Map<Long, UmsAdmin> adminMap = umsAdmins.stream().collect(Collectors.toMap(UmsAdmin::getId, it -> it));
        // 查找回复人的信息

        dtoList.forEach(it -> {
            UmsAdmin umsAdmin = adminMap.get(it.getUid());
            if (umsAdmin != null) {
                it.setAvatar(umsAdmin.getAvatar());
                it.setNickname(umsAdmin.getNickname());
            }
            if (it.getChildren() != null && !CollectionUtils.isEmpty(it.getChildren())) {
                Map<Long, CommentTreeDto> childMap = it.getChildren().stream().collect(Collectors.toMap(CommentTreeDto::getId, it2 -> it2));
                it.getChildren().forEach(child -> {
                    UmsAdmin childAdmin = adminMap.get(child.getUid());
                    if (childAdmin != null) {
                        child.setAvatar(childAdmin.getAvatar());
                        child.setNickname(childAdmin.getNickname());
                    }
                    CommentTreeDto commentTreeDto = childMap.get(child.getToCommentId());
                    if (commentTreeDto!=null){
                        UmsAdmin umsAdmin1 = adminMap.get(commentTreeDto.getUid());
                        if (umsAdmin1 != null) {
                            child.setToCommentNickname(umsAdmin1.getNickname());
                        }
                    }
                });
            }
        });
        return CommonPage.restPage(page, dtoList);
    }

    @Override
    public List<CommentTreeDto> getChildCommentList(Long blogId, Long parentId, int pageNum, int pageSize) {
        return null;
    }

    @Override
    public void add(CmsComment dto) {
        this.baseMapper.insert(dto);
    }

    @Override
    public void edit(CmsComment dto) {
        CmsComment cmsComment = this.baseMapper.selectById(dto.getId());
        if (cmsComment == null) {
            Asserts.fail("不存在");
        }
        this.baseMapper.updateById(dto);
    }

    @Override
    public void del(Long id) {
        CmsComment cmsComment = this.baseMapper.selectById(id);
        if (cmsComment == null) {
            Asserts.fail("不存在");
        }
        this.baseMapper.deleteById(id);
    }
}
